import os
import yaml

class Config:
    """应用配置类 - 支持从YAML文件和环境变量加载配置"""
    # 默认配置
    DEFAULT_CONFIG = {
        'database': {
            'driver': 'mysql+pymysql',
            'username': 'root',
            'password': 'Kdt001@123',
            'host': '101.43.38.178',
            'port': 3306,
            'database_name': 'kitten_tts_db',
            'track_modifications': False
        },
        'app': {
            'secret_key': 'dev-secret-key',
            'debug': True
        },
        'tts': {
            'model_name': 'KittenML/kitten-tts-nano-0.2'
        },
        'logging': {
            'level': 'INFO'
        }
    }
    
    def __init__(self):
        # 加载YAML配置文件
        config_data = self._load_config_file()
        
        # 设置配置属性
        # 数据库URI优先顺序：环境变量 > 完整URI配置 > 分解的配置项
        self.SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
            self._build_database_uri(config_data)
        
        self.SQLALCHEMY_TRACK_MODIFICATIONS = config_data['database']['track_modifications']
        self.SECRET_KEY = os.environ.get('SECRET_KEY') or config_data['app']['secret_key']
        self.DEBUG = config_data['app']['debug']
        self.TTS_MODEL_NAME = config_data['tts']['model_name']
        self.LOG_LEVEL = os.environ.get('LOG_LEVEL') or config_data['logging']['level']
    
    def _build_database_uri(self, config_data):
        """从分解的数据库配置项构建完整的数据库URI"""
        # 优先使用完整URI（如果有设置）
        if 'uri' in config_data['database'] and config_data['database']['uri']:
            return config_data['database']['uri']
        
        # 从分解的配置项构建URI
        db_config = config_data['database']
        driver = db_config.get('driver', 'mysql+pymysql')
        username = db_config.get('username', '')
        password = db_config.get('password', '')
        host = db_config.get('host', 'localhost')
        port = db_config.get('port', 3306)
        database_name = db_config.get('database_name', '')
        
        # 构建URI字符串
        # 处理密码中可能包含的特殊字符（如@符号）
        password_escaped = password.replace('@', '%40')
        return f"{driver}://{username}:{password_escaped}@{host}:{port}/{database_name}"
    
    def _load_config_file(self):
        """从YAML文件加载配置"""
        config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml')
        
        if os.path.exists(config_path):
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config_data = yaml.safe_load(f)
                    # 合并默认配置和文件配置
                    return self._merge_configs(self.DEFAULT_CONFIG, config_data)
            except Exception as e:
                print(f"Warning: Failed to load config file {config_path}: {e}")
        
        # 如果配置文件不存在或加载失败，返回默认配置
        return self.DEFAULT_CONFIG
    
    def _merge_configs(self, default, custom):
        """递归合并默认配置和自定义配置"""
        if not isinstance(custom, dict):
            return default
        
        result = default.copy()
        for key, value in custom.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._merge_configs(result[key], value)
            else:
                result[key] = value
        
        return result

# 创建一个配置实例，保持向后兼容性
config_instance = Config()

# 提取配置属性到模块级别，保持向后兼容性
SQLALCHEMY_DATABASE_URI = config_instance.SQLALCHEMY_DATABASE_URI
SQLALCHEMY_TRACK_MODIFICATIONS = config_instance.SQLALCHEMY_TRACK_MODIFICATIONS
SECRET_KEY = config_instance.SECRET_KEY
DEBUG = config_instance.DEBUG
TTS_MODEL_NAME = config_instance.TTS_MODEL_NAME
LOG_LEVEL = config_instance.LOG_LEVEL